package com.photons.artp.viewmodel

import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.databinding.PropertyChangeRegistry
import androidx.databinding.library.baseAdapters.BR
import androidx.lifecycle.ViewModel
import com.photons.artp.utils.NetUtils

class MainViewModel: ViewModel(), Observable {
    private var peerIP = NetUtils.getPeerIP()

    @Bindable
    fun getPeerIP(): String {
        return peerIP
    }

    fun setPeerIP(value: String) {
        if (peerIP != value) {
            peerIP = value

            NetUtils.savePeerIP(value)

            notifyPropertyChanged(BR.peerIP)
        }
    }

    // 为了在继承ViewModel后，仍然可以被观察（之前要继承BaseObservable），需要自己参考BaseObservable
    // 实现Observable里面的方法
    private val callbacks: PropertyChangeRegistry = PropertyChangeRegistry()

    override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
        callbacks.add(callback)
    }

    override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
        callbacks.remove(callback)
    }

    private fun notifyPropertyChanged(fieldId: Int) {
        callbacks.notifyCallbacks(this, fieldId, null)
    }
}